package com.glory.hikvisionmobile.activity;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.adapter.DrugInfoAdapter;
import com.glory.hikvisionmobile.adapter.EqpKeepInputListAdapter;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.TrackIn.ItemWorkBean;
import com.glory.hikvisionmobile.bean.from.DrugAddBean;
import com.glory.hikvisionmobile.bean.from.DrugBean;
import com.glory.hikvisionmobile.bean.from.DrugInfoBean;
import com.glory.hikvisionmobile.bean.from.DrugInfoListBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.utils.DialogUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class From_AddDrugRecordActivity extends BaseActivity {

    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.etPlatform)
    FreeUI_ClearEditText etPlatform;
    @BindView(R.id.tvTrough)
    TextView tvTrough;
    @BindView(R.id.ivTroughListArrow)
    ImageView ivTroughListArrow;
    @BindView(R.id.flTroughList)
    FrameLayout flTroughList;
    @BindView(R.id.tvDrugName)
    TextView tvDrugName;
    @BindView(R.id.ivDrugNameListArrow)
    ImageView ivDrugNameListArrow;
    @BindView(R.id.flDrugNameList)
    FrameLayout flDrugNameList;
    @BindView(R.id.tvDrugDesc)
    TextView tvDrugDesc;
    @BindView(R.id.tvUnit)
    TextView tvUnit;
    @BindView(R.id.tvReason)
    TextView tvReason;
    @BindView(R.id.ivReasonListArrow)
    ImageView ivReasonListArrow;
    @BindView(R.id.flReasonList)
    FrameLayout flReasonList;
    @BindView(R.id.etRemarks)
    FreeUI_ClearEditText etRemarks;
    @BindView(R.id.etNumber)
    FreeUI_ClearEditText etNumber;
    @BindView(R.id.etDrugInfo)
    FreeUI_ClearEditText etDrugInfo;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.rvDrugInfoList)
    RecyclerView rvDrugInfoList;
    @BindView(R.id.tvReplay)
    TextView tvReplay;
    @BindView(R.id.tvRemove)
    TextView tvRemove;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.nsScroll)
    NestedScrollView nsScroll;
    @BindView(R.id.llSubmitLayout)
    LinearLayout llSubmitLayout;
    private FreeUI_GeneralPop mItemPop;
    private FreeUI_GeneralPop mDrugPop;
    private FreeUI_GeneralPop mDrugReasonPop;
    private List<String> drugList = new ArrayList<>();
    private boolean isFirst = false;
    private List<String> subEquipmentId = new ArrayList<>();
    private List<String> drugReason = new ArrayList<>();
    private DrugAddBean drugAddBean;
    private DrugInfoAdapter drugInfoAdapter;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_from_add_record;
    }

    @Override
    protected void initView() {
        initListTitle();
        rvDrugInfoList.setLayoutManager(new LinearLayoutManager(From_AddDrugRecordActivity.this));
        rvDrugInfoList.setItemAnimator(new DefaultItemAnimator());
        rvDrugInfoList.addItemDecoration(new DividerItemDecoration(From_AddDrugRecordActivity.this, 1));
        drugInfoAdapter = new DrugInfoAdapter(null);
        drugInfoAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        drugInfoAdapter.isFirstOnly(true);
        rvDrugInfoList.setAdapter(drugInfoAdapter);
        Bundle bundle = getIntent().getExtras();
        drugAddBean = (DrugAddBean) bundle.getSerializable("DrugAddBean");
        if (drugAddBean != null) {
            etPlatform.setText(drugAddBean.getEqpId());
            etPlatform.setEnabled(false);
            tvTrough.setText(drugAddBean.getEqpSons());
            flTroughList.setEnabled(false);
            tvDrugName.setText(drugAddBean.getYaoYe());
            flDrugNameList.setEnabled(false);
            tvDrugDesc.setText(drugAddBean.getYaoYeDesc());
            etNumber.setText(drugAddBean.getMainQty());
            etNumber.setEnabled(false);
            tvReason.setText(drugAddBean.getReason());
            flReasonList.setEnabled(false);
            etRemarks.setText(drugAddBean.getComment());
            etRemarks.setEnabled(false);
            tvUnit.setText(drugAddBean.getUnit());
            etDrugInfo.setEnabled(false);
            drugInfoAdapter.setNewData(drugAddBean.getxPdaFormYaoYeLines2());
            drugInfoAdapter.setEnable(false);
            rvDrugInfoList.setEnabled(false);
            llSubmitLayout.setVisibility(View.GONE);
        } else {
            initEdit(etPlatform, s -> requestItem(s));
            try {
                tvTime.setText(FreeApi_DateUtils.longToString(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            initEdit(etDrugInfo, s -> addDrugToList(s),true);
        }

    }

    private void initListTitle() {
        listTv1.setText("名称");
        listTv2.setText("描述");
        listTv3.setText("药液批次");
        listTv4.setText("勾选框");
        listTv1.setVisibility(View.VISIBLE);
        listTv2.setVisibility(View.VISIBLE);
        listTv3.setVisibility(View.VISIBLE);
        listTv4.setVisibility(View.VISIBLE);
    }

    private void addDrugToList(String drugInfo) {
        if (drugInfo.length() < 9){
            showToast("药液信息不符合要求",false);
            return;
        }
        String drugName = tvDrugName.getText().toString().trim();
        String drugDesc = tvDrugDesc.getText().toString().trim();
        String number = etNumber.getText().toString().trim();
        double num;
        if (FreeApi_StringUtils.isEmpty(drugName)){
            showToast("请选择药液信息",false);
            return;
        }

        if (FreeApi_StringUtils.isEmpty(number)) {
            num = 0;
        }else {
            num = Double.parseDouble(number);
        }

        String drugInfoName = drugInfo.substring(0, 9);
        String drugInfoLot = drugInfo.substring(9);
        if (drugInfoName.equals(drugName)){
            etDrugInfo.setText("");
            DrugInfoBean drugInfoBean = new DrugInfoBean(etPlatform.getText().toString().trim(),tvTrough.getText().toString(),drugName,
                    drugDesc,drugInfoLot,tvUnit.getText().toString(),etRemarks.getText().toString(),"");
            drugInfoAdapter.addData(drugInfoBean);
            drugInfoAdapter.notifyDataSetChanged();
            etNumber.setText(String.valueOf(num += 1));
            flTroughList.setEnabled(false);
        }else {
            showToast("药液信息不符合要求",false);
        }
    }

    /**
     * 根据槽体选择药液
     * @param trugName
     */
    private void requestDrugDesc(String trugName) {
        JsonObject map = new JsonObject();
        map.addProperty("subEqpId", trugName);

        NetUtils.requestDara("HIK.PdaFormEqpMaterialLine", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<DrugAddBean>>
                (new TypeToken<BaseResponseBean<DrugAddBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<DrugAddBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    drugList.clear();
                    DrugAddBean drugDescBean = response.body().getBody();
                    for (DrugBean bean : drugDescBean.getxPdaFormEqpMaterialLines()) {
                        drugList.add(bean.getMaterialName() + "/" + bean.getMaterialDesc() + "/" + bean.getUnit());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<DrugAddBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaFormEqpMaterialLine");
            }
        });
    }

    private void requestItem(String platForm) {
        JsonObject map = new JsonObject();
        map.addProperty("actionType", "onlySubEqp");
        map.addProperty("mainEquipmentId", platForm);

        NetUtils.requestDara("HIK.PdaGetSubEqp", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<ItemWorkBean>>
                (new TypeToken<BaseResponseBean<ItemWorkBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<ItemWorkBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    ItemWorkBean body = response.body().getBody();
                    subEquipmentId.clear();
                    if (body.getSubEquipmentId().size() > 0) {
                        subEquipmentId = body.getSubEquipmentId();
                    } else {
                        showToast("未查询到槽体列表",false);
                    }

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<ItemWorkBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaGetSubEqp");
            }
        });

    }

    @Override
    protected void initData() {
        NetUtils.getLotTypeList("YYReasons", "USER", this, getSupportFragmentManager(), new NetUtils.SelectorCallback() {
            @Override
            public void onSuccess(List<String> list) {
                drugReason.clear();
                drugReason.addAll(list);
            }

            @Override
            public void onFail(Throwable e, String messageName) {
                loadError(e, messageName);
            }
        });
    }


    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("药液添加记录表");
        freeUI_titleView.setRightListener("取消", v -> {

            if (drugAddBean != null) {
                return;
            }

            initPermission("Refresh", this, new ActionControlListener() {
                @Override
                public void onControlChangeListener() {
                    tvDrugName.setText("");
                    etNumber.setText("");
                    etPlatform.setText("");
                    tvReason.setText("");
                    etRemarks.setText("");
                    tvDrugDesc.setText("");
                    tvTrough.setText("");
                    tvUnit.setText("");
                    isFirst = false;
                    drugList.clear();
                    subEquipmentId.clear();
                    tvReplay.setText("提交");
                    tvRemove.setVisibility(View.VISIBLE);
                    drugInfoAdapter.setNewData(null);
                    flTroughList.setEnabled(true);
                    mItemPop = null;
                    mDrugPop = null;
                    initData();
                }
            });

        });
        return new FreeUI_AddViewEntity("header", llMain);
    }


    private void submit() {


        if (!editIsEmpty(etNumber, "数量不能为空")) {
            return;
        }

        if (!editIsEmpty(etPlatform, "机台不能为空")) {
            return;
        }

        if (FreeApi_StringUtils.isEmpty(tvReason.getText().toString().trim())) {
            showToast("请选择原因", false);
            return;
        }


        if (FreeApi_StringUtils.isEmpty(tvTrough.getText().toString().trim())) {
            showToast("请选择槽体", false);
            return;
        }

        if (FreeApi_StringUtils.isEmpty(tvDrugName.getText().toString().trim())) {
            showToast("请选择药液名称", false);
            return;
        }

        if (drugInfoAdapter.getData().size() <= 0){
            showToast("请添加药液信息", false);
            return;
        }

        if (isFirst) {
            DialogUtils.showLoginDialog(this, userID -> {
                JsonObject map = new JsonObject();
                DrugInfoListBean drugInfoListBean = new DrugInfoListBean();
                drugInfoListBean.setXPdaFormYaoYeLine(drugInfoAdapter.getData());
                DrugAddBean drugAddBean = new DrugAddBean(etPlatform.getText().toString().trim(),tvTrough.getText().toString().trim(),
                        tvDrugName.getText().toString().trim(),tvDrugDesc.getText().toString().trim(),"",etNumber.getText().toString().trim(),tvReason.getText().toString().trim(),tvUnit.getText().toString(),
                        userID,etRemarks.getText().toString().trim(),tvTime.getText().toString(),drugInfoListBean);
                map.addProperty("actionType", "save");
                map.addProperty("formType", "YY");
                map.add("xPdaFormYaoYe", new JsonParser().parse(new Gson().toJson(drugAddBean)).getAsJsonObject());
                NetUtils.requestDara("HIK.PdaForm", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>
                        (new TypeToken<BaseResponseBean<?>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<?>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                            showConfirmDialog(From_AddDrugRecordActivity.this, "提交成功");
                            isFirst = false;
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<?>> response) {
                        super.onError(response);
                        loadError(response.getException(), "HIK.PdaForm");
                    }
                });
            }, getSupportFragmentManager());
        } else {
            DialogUtils.showLoginDialog(this, Constant.CURRENT_USER, () -> {
                showConfirmDialog("操作人确认成功");
                tvReplay.setText("确认人确认");
                tvRemove.setVisibility(View.GONE);
                isFirst = true;
            }, getSupportFragmentManager());
        }

    }

    @OnClick({R.id.flTroughList, R.id.flDrugNameList, R.id.flReasonList, R.id.tvReplay, R.id.tvRemove})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flTroughList:
                if (etPlatform.getText().toString().trim().length() == 0) {
                    showToast("机台号不能为空", false);
                    etPlatform.setText("");
                    etPlatform.requestFocus();
                    return;
                }
                if (mItemPop != null) {
                    if (mItemPop.isShowing()) {
                        mItemPop.dismiss();
                    }
                } else {
                     mItemPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flTroughList.getWidth(), subEquipmentId, ivTroughListArrow, (code, i) -> {
                         tvTrough.setText(code);
                         requestDrugDesc(code);
                     });
                }
                FreeApi_PopUtils.setArrowShow(ivTroughListArrow);
                mItemPop.showAsDropDown(flTroughList, 0, 0);
                break;
            case R.id.flDrugNameList:
                if (drugList.size() <= 0) {
                    showToast("未请求到药液列表", false);
                    return;
                }
                if (mDrugPop != null) {
                    if (mDrugPop.isShowing()) {
                        mDrugPop.dismiss();
                    }
                } else {
                    mDrugPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flDrugNameList.getWidth(), drugList, ivDrugNameListArrow, (code, i) -> {
                        String[] drug = code.split("/");
                        tvDrugName.setText(drug[0]);
                        tvDrugDesc.setText(drug[1]);
                        tvUnit.setText(drug[2]);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivDrugNameListArrow);
                mDrugPop.showAsDropDown(flDrugNameList, 0, 0);
                break;
            case R.id.flReasonList:
                if (drugReason.size() <= 0) {
                    showToast("未请求到原因列表", false);
                    return;
                }

                if (mDrugReasonPop != null) {
                    if (mDrugReasonPop.isShowing()) {
                        mDrugReasonPop.dismiss();
                    }
                } else {
                    mDrugReasonPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flReasonList.getWidth(), drugReason, ivReasonListArrow, (code, i) -> {
                        String[] reason = code.split("/");
                        tvReason.setText(reason[0]);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivReasonListArrow);
                mDrugReasonPop.showAsDropDown(flReasonList, 0, 0);
                break;
            case R.id.tvReplay:

                initPermission("Submit", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {

                        submit();
                    }
                });

                break;
            case R.id.tvRemove:
                if (drugInfoAdapter.getRemoveList().size() > 0) {
                    if (drugInfoAdapter.getRemoveList().size() == drugInfoAdapter.getData().size()){
                        drugInfoAdapter.setNewData(null);
                        etNumber.setText("");
                        return;
                    }
                    for (int i = drugInfoAdapter.getRemoveList().size() - 1; i >= 0 ; i--) {
                        drugInfoAdapter.remove(Integer.parseInt(drugInfoAdapter.getRemoveList().get(i)));
                    }
                    etNumber.setText(String.valueOf(drugInfoAdapter.getData().size()));
                }
                drugInfoAdapter.getRemoveList().clear();
                break;
        }
    }
}
